package com.xncoding.jwt.config.handler;

import cn.hutool.core.thread.ThreadUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.springframework.util.StringUtils;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;

/**
 * 类描述：socket服务器端处理类
 * @author Wang Haifeng
 * @date - 2018-12-14
 */
@Slf4j
public class ServerHandler extends IoHandlerAdapter {
	private Map<Long,IoSession> sessionMap = new ConcurrentHashMap<>();
	public boolean sendToAllSession(String content){
		for (IoSession session : sessionMap.values()) {
			try {
				session.write(content+"\n");
			}catch (Exception e){
				log.error("------推送消息异常------>"+session.getId()+"------>"+content,e);
			}
		}
		return true;
	}
	@Override
	public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
		log.error("出现异常 :" + session.getRemoteAddress().toString() + " : " + cause.toString());
		session.write("出现异常");
		session.closeNow();
		sessionMap.remove(session.getId());
	}

	@Override
	public void sessionCreated(IoSession session) throws Exception {
		log.info(session.getId()+"连接创建 : " + session.getRemoteAddress().toString());
		sessionMap.put(session.getId(),session);
	}

	@Override
	public void sessionOpened(IoSession session) throws Exception {
		log.info(session.getId()+"连接打开: " + session.getRemoteAddress().toString());
		session.write("---连接成功\n");
	}

	@Override
	public void messageReceived(IoSession session, Object message) throws Exception {
		if(null == message || !StringUtils.hasText(message.toString()))
			return;
		String address = session.getLocalAddress().toString();
		log.info("服务器["+address+"]接受到数据 :" + String.valueOf(message));
		String text = String.valueOf(message);
		log.info("数据业务处理开始...... "+session.getId());
		String result = analyzeData(text, session);
		log.info("数据业务处理结束...... ");
		session.write(result);

	}

	private String analyzeData(String text, IoSession session) throws InterruptedException, ExecutionException {
		String address = session.getLocalAddress().toString();
		ThreadUtil.sleep(10000L);
		String responseMessage = "test".equals(text) ? "1111" : "收到啦！";
		return responseMessage;
	}

	@Override
	public void messageSent(IoSession session, Object message) throws Exception {
		log.info("返回客户端消息 : "+message);
//		session.write(message);
	}

	@Override
	public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
		if (status == IdleStatus.READER_IDLE) {
			log.info("进入读空闲状态");
			session.closeNow();

			sessionMap.remove(session.getId());
		} else if (status == IdleStatus.BOTH_IDLE) {
			log.info("BOTH空闲");
			session.closeNow();

			sessionMap.remove(session.getId());
		}
	}

	@Override
	public void sessionClosed(IoSession session) throws Exception {
		log.info("连接关闭 : " + session.getRemoteAddress().toString());
		int size = session.getService().getManagedSessions().values().size();
		log.info("连接关闭时session数量==》" + size);

		sessionMap.remove(session.getId());
	}

}
